<?php

use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Overtrue\LaravelWeChat\Facade as EasyWeChat;
use Illuminate\Support\Facades\Cache;

if (!function_exists('file_url')) {
    function file_url($file, $style = null, $store = 'file')
    {
        if (is_null($file) || empty($file)) {
            return null;
        }

        if (is_array($file)) {
            return array_map(function ($file) use ($style) {
                return file_url($file, $style);
            }, $file);
        }

        return \App\Library\OSS::instance($store)->getUrl($file);
    }
}

if (!function_exists('str_split_unicode')) {
    function str_split_unicode($str, $l = 0)
    {
        if ($l > 0) {
            $ret = array();
            $len = mb_strlen($str, "UTF-8");
            for ($i = 0; $i < $len; $i += $l) {
                $ret[] = mb_substr($str, $i, $l, "UTF-8");
            }
            return $ret;
        }
        return preg_split("//u", $str, -1, PREG_SPLIT_NO_EMPTY);
    }

}

if (!function_exists('filterEmoji')) {
    function filterEmoji($str)
    {
        $str = preg_replace_callback(
            '/./u',
            function (array $match) {
                return strlen($match[0]) >= 4 ? '' : $match[0];
            },
            $str);

        return $str;
    }
}

if (!function_exists('curl_post')) {
    function curl_post($url, $data)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        $response = curl_exec($ch);
        curl_close($ch);
//        echo $response;
        return $response;
    }
}

function sendSystem($user, $template_id, $sendData)
{
    Log::channel('pay')->info("触发的商家职员信息-{$template_id}：", $user);
    if ($user) {
        foreach ($user as $openid) {
            if($openid['is_palm_management'] == 1){
                $sendData[0] = $openid["openid"];
                sendMessage($template_id, $sendData);
            }
        }
    }
}

/**
 * 发送模板消息的统一封装
 * @param $template_id
 * @param $data
 */
function sendMessage($template_id = 0, $data = [])
{
    $template = DB::table("templates")->where('status', 1)->find($template_id);

    if (isset($template)) {

        $sendData = [
            "touser" => $data[0],
            "mp_template_msg" => [
                "appid" => env("WECHAT_OFFICIAL_ACCOUNT_APPID"),
                'template_id' => $template->template_id,
                'data' => [
                    'first' => ['value' => json_decode($template->json, true)['first']],
                    'remark' => ['value' => json_decode($template->json, true)['remark']],
                ],
            ]
        ];
        $json = count(json_decode($template->json, true));

        if (isset($data['first'])) {
            $sendData['mp_template_msg']['data']['first'] = ['value' => $data['first']];
        }
        for ($i = 1; $i <= $json - 2; $i++) {
            $sendData['mp_template_msg']['data']['keyword' . $i] = ['value' => $data[$i]];
        }

        // uniformMessage($sendData);
    }


}

/**
 * 发生统一服务消息
 * @param $url
 * @param $data
 * @return string
 */
if (!function_exists('uniformMessage')) {
    function uniformMessage($data, $num = 1)
    {
        $app = EasyWeChat::miniProgram();
        $accessToken = $app->access_token;
        $access_token = $accessToken->getToken()['access_token']; // token 数组  token['access_token'] 字符串
        $data = json_encode($data);
        $url = 'https://api.weixin.qq.com/cgi-bin/message/wxopen/template/uniform_send?access_token=' . $access_token;
        $result = curl_post($url, $data);
        $result = json_decode($result);
        Log::channel('pay')->info("每次发送的模板消息数据：", json_decode($data, true));
        Log::channel('pay')->info("uniformMessage", ["errcode" => $result->errcode, "errmsg" => $result->errmsg]);
        if ($num >= 3) {
            Log::channel('pay')->info("发生错误超过三次：", json_decode($data, true));
            return "fail";
        }
        if ($result->errcode == '0' && $result->errmsg == 'ok') {
            return 'success';
        } else {
            if ($result->errcode == '40001') {
                $accessToken->getToken(true); // token 数组  token['access_token'] 字符串
                uniformMessage(json_decode($data, true), $num + 1);
            }
            if ($result->errcode == '40003') {
                Log::channel('pay')->info("报错40003之后的data数据：", json_decode($data, true));
                uniformMessage(json_decode($data, true), $num + 1);
            }
            return 'fail';
        }
    }
}

function getAccessToken()
{
//    $accessToken = Cache::store('file')->get("accessToken");
//    if ($accessToken) {
//        return $accessToken;
//    } else {

    $appid = env("WECHAT_MINI_PROGRAM_APPID");
    $secret = env("WECHAT_MINI_PROGRAM_SECRET");
    $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$appid}&secret={$secret}";
    $res = curl_get($url);
    $res = json_decode($res, 1);
    Cache::store('file')->put("accessToken", $res['access_token'], 3600);
    return $res['access_token'];
//    }

}

function curl_get($url)
{
    $headers = array('User-Agent:Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.81 Safari/537.36');
    $oCurl = curl_init();
    if (stripos($url, "https://") !== FALSE) {
        curl_setopt($oCurl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($oCurl, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($oCurl, CURLOPT_SSLVERSION, 1); //CURL_SSLVERSION_TLSv1
    }
    curl_setopt($oCurl, CURLOPT_TIMEOUT, 20);
    curl_setopt($oCurl, CURLOPT_URL, $url);
    curl_setopt($oCurl, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($oCurl, CURLOPT_RETURNTRANSFER, 1);
    $sContent = curl_exec($oCurl);
    $aStatus = curl_getinfo($oCurl);
    curl_close($oCurl);
    if (intval($aStatus["http_code"]) == 200) {
        return $sContent;
    } else {
        return false;
    }
}
